﻿(function ($) {
	var defaultOptions = {
		content: '#main-content',
		TextIdPrefix: 'text-',
		EditContentUrl: '',
		PartHead: '.part-head',
		CurrentUrl: null,
		BookHashTag: null,
	};

	function init(opt) {
		var options = $.extend({}, defaultOptions, opt);
		options.$el = $(options.content);
		
		rangyInputs.init();

		addEditLinks(options);

		$(window).trigger('resize');
	}

	function addEditLinks(options) {
		var $texts = $('[id^="' + options.TextIdPrefix + '"]', options.$el);

		$($(options.PartHead), options.$el).after(createNewTemplateDiv(-1, { options: options }));

		$texts.each(function () {
			var $this = $(this);
			var id = $this.attr('id').substring(options.TextIdPrefix.length);
			if (!Number(id))
				return;
			$this.after(createNewTemplateDiv(id, { options: options }));
			$this.before(prefix(id, options));
		});
	}

	function createNewTemplateDiv(afterTextId, base) {
		var $div = $('<div />').addClass('edit-new');
		$.each({
			p: 'p',
			ul: 'ul',
			ol: 'ol',
			code: 'code',
			img: 'img',
			block: 'block',
			table: 'table',
			'element-table': 'element-table',
			h3: 'h3',
			h4: 'h4',
			h5: 'h5',
			h6: 'h6',
			'listing-note': 'listing-note'
		}, function (key, value) {
			var $template = $('<a/>').addClass('ui-link').bind('click', function (e) {
				e.preventDefault();
				var $ta = $('<textarea />');
				rangyInputs.enableTabIndentation($ta[0], "\t");
				$ta.val(template($(this).attr('tag'), base.options.BookHashTag));
				$(this).parent().after($ta).hide();
				var save = getArrayObjectByName(mySettings.markupSet, 'Save');
				save.beforeInsert = function (markItUp) {
					$.ajax({
						type: 'POST',
						url: base.options.EditContentUrl,
						data: { afterTextId: afterTextId, text: htmlEncode(markItUp.textarea.value), parentTag: base.options.CurrentUrl },
						dataType: 'json',
						success: function (data) {
							location.reload(false); 
							//window.location.reload(true);
						},
						error: function (data) {
							alert(data.responseText);
						},
					});
				};
				//bindAnchorEditorButton(currentChapterUrl, mySettings);

				$ta.markItUp(mySettings);
			});
			var $t = $template.clone(true).attr('tag', key).text(value);
			$div.append($t).append('&nbsp;&nbsp;');
		});
		return $div;
	}
	
	function prefix(id, options) {
		var $div = $('<div />').addClass('edit-a');
		var $edit = $('<a />').attr('taghash', id).text('edit').bind('click', function (e) {
			e.preventDefault();
			var textId = $(this).attr('taghash');

			$('div.edit-a a[taghash=' + textId + ']').hide();
			$('#' + options.TextIdPrefix + textId).addClass('highlight');

			$.ajax({
				type: 'GET',
				url: options.EditContentUrl,
				data: { hashTag: options.CurrentUrl, textId: textId },
				dataType: 'json',
				success: function (data) {
					var $ta = $('<textarea />');
					rangyInputs.enableTabIndentation($ta[0], "\t");
					$ta.val(data.Result);
					$('#' + options.TextIdPrefix + data.TextId).after($ta).hide();
					var save = getArrayObjectByName(mySettings.markupSet, 'Save');
					save.beforeInsert = function (markItUp) {
						$.ajax({
							type: 'PUT',
							url: options.EditContentUrl,
							data: { hashTag: options.CurrentUrl, /*textId: data.TextId, */text: htmlEncode(markItUp.textarea.value) },
							dataType: 'json',
							success: function (data) {
								location.reload(false);
								//window.location.reload(true);
							}
						});
					};

					//bindAnchorEditorButton(currentChapterUrl, mySettings);

					$ta.markItUp(mySettings);

					//insertEditor(taghash, data.Content, onEditEditorCreated, SaveEdit);
				}
			});
		});
		var $delete = $('<a />')/*.attr('href', editUrl.replace('-1', id))*/.attr('taghash', id).text('delete').bind('click', function (e) {
			e.preventDefault();
			var textId = $(this).attr('taghash');

			$('div.edit-a a[taghash=' + textId + ']').hide();
			$('#' + options.TextIdPrefix + textId).addClass('highlight');

			$.ajax({
				type: 'DELETE',
				url: options.EditContentUrl,
				data: { hashTag: options.CurrentUrl, textId: $(this).attr('taghash') },
				dataType: 'json',
				success: function (data) {
					location.reload(false);
					//window.location.reload(true);
				}
			});
		});

		$div.append($edit).append('&nbsp;&nbsp;').append($delete);
		return $div;
	}


	/*****************/
		function onEditCheckBoxStatus($checkbox) {
			var isChecked = $checkbox.is(':checked');
			if (isChecked) {
			} else {
				var $editDivs = $('div.edit-a', base.$el);
				$('a', $editDivs).unbind('click');
				$editDivs.remove();
				
				var $newDivs = $('div.edit-new', base.$el);
				$('a', $newDivs).unbind('click');
				$newDivs.remove();
			}
			
			$.SmarlyStorage.set("edit-content", isChecked);


		
		base.init();
	};

	function getArrayObjectByName(array, name) {
		for (var i = 0; i < array.length; i++) {
			if (array[i].name == name)
				return array[i];
		}

		return null;
	}

	function template(name, bookHashTag) {
		switch (name) {
			case 'p':
				return '[p][/p]';
			case 'ul':
				return '[ul][li][/li][/ul]';
			case 'ol':
				return '[ol][li][/li][/ol]';
			case 'h3':
				return '[h3][/h3]';
			case 'h4':
				return '[h4][/h4]';
			case 'h5':
				return '[h5][/h5]';
			case 'h6':
				return '[h6][/h6]';

			case 'block':
				return '[div][blockquote][p][b][/b][/p][p][/p][/blockquote][/div]';
			case 'img':
				return '[div][blockquote][b]Рисунок #1-#2:[/b] #3[/blockquote][img=http://storage.smarly.net/' + bookHashTag + '/#1.#2.png][/div]';
			case 'table':
				return '[div][blockquote][b]Таблица #1-#2:[/b] #3[/blockquote][table=table table-bordered][thead]\r\n[tr]\r\n[td][/td]\r\n[td][/td]\r\n[/tr]\r\n[/thead]\r\n[tbody]\r\n[tr]\r\n[td][/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td][/td]\r\n[td][/td]\r\n[/tr]\r\n[/tbody][/table][/div]';
			case 'element-table':
				return '[div][blockquote][b]Таблица #1-#2:[/b] #3[/blockquote][table=table table-bordered][tbody]\r\n[tr]\r\n[td]Элемент[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Тип элемента[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Разрешенные родительские элементы[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Локальные атрибуты[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Содержание[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Стиль тегов[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Новый в HTML5[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Изменения в HTML5[/td]\r\n[td][/td]\r\n[/tr]\r\n[tr]\r\n[td]Соглашение по стилям[/td]\r\n[td][/td]\r\n[/tr][/tbody][/table][/div]';
			case 'code':
				return '[div][blockquote][b]Листинг #1-#2:[/b] #3[/blockquote][pre=xml][/pre][/div]';
			case 'listing-note':
				return '[div][blockquote][p]Строка [b]#[/b]: text[/p][/blockquote][/div]';
		}
		return '';
	}
	
	function htmlEncode(value) {
		return value.replace(/\[pre=.+?](\s|.)+?\[\/pre]/gim, function (match) {
			return $('<div/>').text(match).html();
		});
		//create a in-memory div, set it's inner text(which jQuery automatically encodes)
		//then grab the encoded contents back out.  The div never exists on the page.
		return $('<div/>').text(value).html();
	}

	function htmlDecode(value) {
		return $('<div/>').html(value).text();
	}

	
/*	function bindEncodingEditorButton(mySettings)
	{
		var chapterElementsLink = getArrayObjectByName(mySettings.markupSet, 'EncodingLink');
		chapterElementsLink.beforeInsert = function (markItUp) {
			markItUp.textarea.value = markItUp.textarea.value.replace(new RegExp('<', 'igm'), '&lt;');
		};
	}*/
	
	function bindAnchorEditorButton(currentChapterUrl, mySettings) {
		var chapterElementsLink = getArrayObjectByName(mySettings.markupSet, 'ElementsLink');
		chapterElementsLink.beforeInsert = function (markItUp) {
			$.ajax({
				type: 'POST',
				url: /*base.options.EditContentUrl*/'/admin/EditContext/ChaptersElements',
				data: { hashTag: currentChapterUrl.substring(1) },
				dataType: 'json',
				success: function (data) {
					var $t = $('<table class="table table-bordered"><thead><tr><td>Главы</td>' +
						'<td>Листинги</td>' +
						'<td>Картинки</td>' +
						'<td>Таблицы</td>' +
						'</tr>' +
						'</thead>' +
						'<tbody>' +
						'</tbody></table>');

					var $chaptersRadio = $('<div><input style="display:inline;" type="radio" name="chapter_radio" id="chapter_radio_" /><label for="chapter_radio_" style="display:inline;"k></label></div>');

					var datachapters = data.Chapters;
					var datalistings = data.Listings;
					var datafigures = data.Figures;
					var datatables = data.Tables;

					var maxLength = datachapters.length > datalistings.length ? datachapters.length : datalistings.length;
					maxLength = maxLength > datafigures.length ? maxLength : datafigures.length;
					maxLength = maxLength > datatables.length ? maxLength : datatables.length;

					var addradio = function ($row, array, index) {
						var $td = $('<td />');
						if (index < array.length) {
							var dc = array[index];
							var $rd = $chaptersRadio.clone();
							var $r = $('input', $rd);
							var $l = $('label', $rd);

							var rid = new Date().getTime() + '' + Math.floor((Math.random() * 10000) + 1);
							$r.attr('id', $r.attr('id') + rid);
							$l.attr('for', $r.attr('id'));

							$l.text(dc.Title);
							$r.data('value', dc.Value);
							$td.append($r).append($l);
						}
						$row.append($td);
					};

					for (var i = 0; i < maxLength; i++) {
						var $tr = $('<tr />');
						addradio($tr, datachapters, i);
						addradio($tr, datalistings, i);
						addradio($tr, datafigures, i);
						addradio($tr, datatables, i);

						$('tbody', $t).append($tr);
					};

					$.SmarlyModal.show({
						body: $t,
						showCancelBtn: false,
						onHideModal: function () {

							var $chb = $('input:checked', this);

							if ($chb.length == 0)
								return;

							var url = $chb.data('value');

							var markItUpObj = markItUp;

							var b = $(markItUpObj.textarea).val().substring(0, markItUpObj.caretPosition);
							var c = $(markItUpObj.textarea).val().substring(markItUpObj.caretPosition, markItUpObj.caretPosition + markItUpObj.selection.length);
							var e = $(markItUpObj.textarea).val().substring(markItUpObj.caretPosition + markItUpObj.selection.length);

							$(markItUpObj.textarea).val(b + '[url=' + url + ']' + c + '[/url]' + e);

						},
					});
				}
			});


		};
		var chapterLink = getArrayObjectByName(mySettings.markupSet, 'ChapterLink');
		chapterLink.beforeInsert = function (markItUp) {
			$.SmarlyModal.show({
				fullScreen: true,
				body: $('<div/>').append($('<iframe src="' + currentChapterUrl + '?isAddUrl=true" width="100%" height="800px" id="frameSmarly"></iframe>')),
				onHideModal: function () {
					var iframeChapter = document.getElementById('frameSmarly').contentWindow['currentChapterUrl'];

					if (currentChapterUrl == iframeChapter)
						iframeChapter = '';

					var iframeTextId = document.getElementById('frameSmarly').contentWindow['selectedTextId'];
					if (iframeTextId == null)
						iframeTextId = '';
					else
						iframeTextId = '#' + iframeTextId;
					var url = iframeChapter + iframeTextId;

					var markItUpObj = markItUp;

					var b = $(markItUpObj.textarea).val().substring(0, markItUpObj.caretPosition);
					var c = $(markItUpObj.textarea).val().substring(markItUpObj.caretPosition, markItUpObj.caretPosition + markItUpObj.selection.length);
					var e = $(markItUpObj.textarea).val().substring(markItUpObj.caretPosition + markItUpObj.selection.length);

					$(markItUpObj.textarea).val(b + '[url=' + url + ']' + c + '[/url]' + e);

					/*
														markItUpObj.replaceWith(url);
														markItUpObj.TextIdUrl = url;
					*/
				},
			});
		};

	}

	

	$.extend({
		SmarlyAdminPageContent: init,
	});

})(jQuery);







/*










function prefix(id) {
	var $div = $('<div />').addClass('edit-a');
	var $edit = $('<a />').addClass('ui-link').attr('href', editUrl.replace('-1', id)).attr('taghash', id).text('edit').bind('click', OnEditClick);
	var $delete = $('<a />').addClass('ui-link').attr('href', editUrl.replace('-1', id)).attr('taghash', id).text('delete').bind('click', OnDeleteClick);

	$div.append($edit).append('&nbsp;&nbsp;').append($delete);
	return $div;
}

function postfix(id) {
	var $div = $('<div />').addClass('edit-new');

	var tags = {
		p: 'p',
		ul: 'ul',
		ol: 'ol',
		code: 'code',
		img: 'img',
		block: 'block',
		table: 'table',
		h1: 'h1',
		h2: 'h2',
		h3: 'h3',
		h4: 'h4',
		h5: 'h5'
	};

	var $template = $('<a/>').addClass('ui-link').bind('click', OnNewElementClick);

	$.each(tags, function (key, value) {
		var $t = $template.clone(true).attr('taghash', id).attr('tag', key).text(value);
		$div.append($t).append('&nbsp;&nbsp;');
	});

	return $div;
}

$(document).ready(function () {
	if (typeof editUrl == 'undefined' || typeof viewUrl == 'undefined') {
		alert('EditUrl or ViewUrl undefined');
		return;
	}

	var data = { Content: $('#main-content') };
	$('[id^="text-"]', $(data.Content)).each(function () {
		var $this = $(this);
		var id = $this.attr('id');
		if (!Number(id))
			return;
		$this.before(prefix(id));
		$this.after(postfix(id));
	});
});

var dialogPreValue = {
	codeClass: null,
	chapterNum: 0,
	codeNum: 1,
	imgNum: 1,
	tableNum: 1
};

function dialogSettings(name, taghash) {
	var result = null;
	switch (name) {
		case 'code':
			result =
			{
				mode: 'button',
				headerText: 'Code...',
				headerClose: true,
				buttons: {
					'Создать': {
						click: function (a, b, c) {
							var content = template(name);

							var self = $(this.sdIntContent);

							var chapter = $('.major', self).val();
							var num = $('.minor', self).val();
							dialogPreValue['codeClass'] = $('select.code-classes option:selected', self).val();

							var chapterInt = parseInt(chapter);

							if (chapterInt != null)
								dialogPreValue['chapterNum'] = chapterInt;

							var codeNumInt = parseInt(num);

							if (codeNumInt != null)
								dialogPreValue['codeNum'] = codeNumInt;

							content = content.replace(/#1/gi, chapter);
							content = content.replace(/#2/gi, num);
							content = content.replace(/#3/gi, $('.name', self).val());
							content = content.replace(/#4/gi, dialogPreValue['codeClass']);

							$('div.edit-a a[taghash=' + taghash + ']').hide();

							insertEditor(taghash, content, onNewEditorCreated, SaveNew);

							this.close();
						}
					},
					'Cancel': {
						click: function () {
							this.close();
						},
						icon: "delete",
						theme: "c"
					}
				}
			};
			break;
		case 'img':
			result =
			{
				mode: 'button',
				headerText: 'Img...',
				headerClose: true,
				buttons: {
					'Создать': {
						click: function (a, b, c) {
							var content = template(name);

							var self = $(this.sdIntContent);

							var chapter = $('.major', self).val();
							var num = $('.minor', self).val();

							var chapterInt = parseInt(chapter);
							if (chapterInt != null)
								dialogPreValue['chapterNum'] = chapterInt;

							var imgNumInt = parseInt(num);
							if (imgNumInt != null)
								dialogPreValue['imgNum'] = imgNumInt;

							content = content.replace(/#1/gi, chapter);
							content = content.replace(/#2/gi, num);
							content = content.replace(/#3/gi, $('.name', self).val());

							$('div.edit-a a[taghash=' + taghash + ']').hide();

							insertEditor(taghash, content, onNewEditorCreated, SaveNew);

							this.close();
						}
					},
					'Cancel': {
						click: function () {
							this.close();
						},
						icon: "delete",
						theme: "c"
					}
				}
			};
			break;
		case 'table':
			result =
			{
				mode: 'button',
				headerText: 'Table...',
				headerClose: true,
				buttons: {
					'Создать': {
						click: function (a, b, c) {
							var content = template(name);

							var self = $(this.sdIntContent);

							var chapter = $('.major', self).val();
							var num = $('.minor', self).val();

							var chapterInt = parseInt(chapter);
							if (chapterInt != null)
								dialogPreValue['chapterNum'] = chapterInt;

							var tableNumInt = parseInt(num);
							if (tableNumInt != null)
								dialogPreValue['tableNum'] = tableNumInt;

							content = content.replace(/#1/gi, chapter);
							content = content.replace(/#2/gi, num);
							content = content.replace(/#3/gi, $('.name', self).val());

							$('div.edit-a a[taghash=' + taghash + ']').hide();

							insertEditor(taghash, content, onNewEditorCreated, SaveNew);

							this.close();
						}
					},
					'Cancel': {
						click: function () {
							this.close();
						},
						icon: "delete",
						theme: "c"
					}
				}
			};
			break;
	}
	return result;
}

function template(name) {
	switch (name) {
		case 'p':
			return '<p>&nbsp;</p>';
		case 'ul':
			return '<ul><li>&nbsp;</li></ul>';
		case 'ol':
			return '<ol><li>&nbsp;</li></ol>';
		case 'h1':
			return '<h1>&nbsp;</h1>';
		case 'h2':
			return '<h2>&nbsp;</h2>';
		case 'h3':
			return '<h3>&nbsp;</h3>';
		case 'h4':
			return '<h4>&nbsp;</h4>';
		case 'h5':
			return '<h5>&nbsp;</h5>';

		case 'block':
			return '<div><blockquote><p>&nbsp;<p></blockquote></div>';
		case 'img':
			return '<div><blockquote><strong>Figure #1-#2:</strong> #3</blockquote><img alt="" src="https://sites.google.com/site/storagesmarlynet/home/#1.#2.png" /></div>';
		case 'table':
			return '<div><blockquote><strong>Table #1-#2:</strong> #3</blockquote><table><thead><tr><td>&nbsp;</td><td>&nbsp;</td></thead><tbody><tr><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr></tbody></table></div>';
		case 'code':
			return '<div><blockquote><strong>Listing #1-#2:</strong> #3</blockquote><pre class="#4">&nbsp;</pre></div>';
	}
	return '';
}





/*********************edit******************#1#

function OnEditClick(e) {
	e.preventDefault();

	var url = $(this).attr('href');
	var taghash = $(this).attr('taghash');

	$('div.edit-a a[taghash=' + taghash + ']').hide();
	$('#' + taghash).addClass('highlight');

	$.ajax({
		type: 'GET',
		url: url,
		data: {},
		dataType: 'json',
		success: function (data) {
			insertEditor(taghash, data.Content, onEditEditorCreated, SaveEdit);
		}
	});
}


function onEditEditorCreated(el) {
	this.resetDirty();
	$('#' + this.config.taghash).hide();
}

function SaveEdit(editor, content) {
	var taghash = editor.config.taghash;

	$.ajax({
		type: 'PUT',
		url: editUrl.replace('-1', taghash),
		data: { Content: content },
		dataType: 'json',
		success: function (data) {
			if (data.Error != null) {
				alert(data.Error);
				return;
			}

			editor.setData(data.Content, function (evt) {
				$.ajax({
					type: 'GET',
					url: viewUrl.replace('-1', taghash),
					data: {},
					dataType: 'json',
					success: function (data) {
						$('#' + taghash, $('.chapter')).replaceWith($(data.Content).hide().addClass('highlight'));
						editor.resetDirty();
						editorStatusbarAddText(editor, '<span style="color: green;">Сохраненно: ' + new Date().toLocaleString() + '</span>, ');
						if (!closeEditor()) {
							return;
						}
					}
				});
			});

		}
	});
}

/*********************edit******************#1#

/*********************new ******************#1#

function OnNewElementClick(e) {
	e.preventDefault();

	if (!closeEditor()) {
		return false;
	}

	var taghash = $(this).attr('taghash');
	var createdTag = $(this).attr('tag');

	var tagdialog = dialogSettings(createdTag, taghash);

	if (tagdialog == null) {
		var content = template(createdTag);
		$('div.edit-a a[taghash=' + taghash + ']').hide();

		insertEditor(taghash, content, onNewEditorCreated, SaveNew);
	}
	else {
		var div = $('#' + createdTag + '-dialog').clone().removeAttr('id').attr('id', taghash + '-dialog').hide();
		$('[data-role=none]', div).removeAttr('data-role');
		$('#' + taghash).after(div);

		$.each(dialogPreValue, function (key, value) {
			$('[name=' + key + ']', div).each(function () {
				var tag = this.nodeName.toLowerCase();
				if (tag == 'input') {
					var v = value;
					if ($(this).attr('inc') != undefined && typeof value === 'number') {
						v++;
					}
					$(this).val(v).attr('value', v);
				} else if (tag == 'select') {
					$(this).find("option[value='" + value + "']").attr('selected', 'selected');
				}
			});
		});

		div.simpledialog2($.extend({}, { buttonPrompt: div.html() }, tagdialog));

	}
	return false;
}

function onNewEditorCreated(el) {
	this.resetDirty();
}

function SaveNew(editor, content) {
	var taghash = editor.config.taghash;

	$.ajax({
		type: 'POST',
		url: editUrl.replace('-1', taghash),
		data: { Content: content },
		dataType: 'json',
		success: function (data) {
			if (data.Error != null) {
				alert(data.Error);
				return;
			}

			editor.resetDirty();
			if (!closeEditor()) {
				return;
			}

			var newId = $(data.Content).attr('id');

			$.ajax({
				type: 'GET',
				url: viewUrl.replace('-1', newId),
				data: {},
				dataType: 'json',
				success: function (data) {
					var $previewContent = $(data.Content);
					$('#' + taghash, $('.chapter')).next().after($previewContent);
					$previewContent.before(prefix(newId));
					$previewContent.after(postfix(newId));
				}
			});
		}
	});
}

/*********************new ******************#1#

/*********************delete ******************#1#

function OnDeleteClick(e) {
	e.preventDefault();
	var taghash = $(this).attr('taghash');
	$('#' + taghash).addClass('highlight');

	$.ajax({
		type: 'DELETE',
		url: editUrl.replace('-1', taghash),
		data: {},
		dataType: 'json',
		success: function (data) {
			if (data.Error != null) {
				alert(data.Error);
				return;
			}

			$('#' + taghash, $('.chapter')).remove();
			$('a[taghash=' + taghash + ']').parent().remove();
		}
	});

}

/*********************delete ******************#1#
*/
